import 'package:library_base/entities/account_rule_entity.dart';
import 'package:library_base/entities/car_entity.dart';
import 'package:library_base/entities/driver_entity.dart';
import 'package:library_base/entities/goods_child_entity.dart';
import 'package:library_base/entities/shipper_entity.dart';
import 'package:library_base/entities/suppliers_entity.dart';
import 'package:library_base/entities/task_detail_entity.dart';
import 'package:library_base/entities/warehouse_entity.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/net/apis.dart';
import 'package:library_base/network/http_config.dart';
import 'package:library_base/provider/base_controller.dart';
import 'package:get/get.dart';
import 'package:library_base/route/routers.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/utils/date_util.dart';
import 'package:library_base/utils/picker/time_picker.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/utils/get_util.dart';

class CreateDeliveryNoteController extends BaseController {
  var loadingTime = '';

  Rxn<SuppliersEntity?> supplier = Rxn<SuppliersEntity?>();

  Rxn<WarehouseEntity?> warehouse = Rxn<WarehouseEntity?>();

  Rxn<AccountRuleEntity?> accountRuleEntity = Rxn<AccountRuleEntity?>();

  Rxn<ShipperEntity?> consignor = Rxn<ShipperEntity?>();

  Rxn<TaskDetailEntity?> taskDetailEntity = Rxn<TaskDetailEntity?>();

  Rxn<CarEntity?> car = Rxn<CarEntity?>();

  Rxn<DriverEntity?> driver = Rxn<DriverEntity?>();

  Rx<double> commodityQuantity = 0.0.obs;

  Rx<double> freight = 0.0.obs;

  DateTime? currentTime;

  List? distributionDetailReqList;

  var loginEnabled = false.obs;

  late Function() callback;

  /// 实体类
  RxList<GoodsChildEntity> listDataSelected = <GoodsChildEntity>[].obs;

  @override
  Future requestData() {
    commodityQuantity.value = getArguments()['totalCount'];
    currentTime = getArguments()['currentTime'];
    distributionDetailReqList = getArguments()['distributionDetailReqList'];
    callback = getArguments()['callback'];
    distributionDetailReqList = getArguments()['distributionDetailReqList'];
    loginEnabled.value = isCanSubmit();
    baseState!.setSafeState();
    return super.requestData();
  }

  chooseLoadingTime() {
    DatePicker.showDateTimePicker(context!,
        showTitleActions: true,
        minTime: DateTime(2021, 1, 1, 00, 00),
        maxTime: DateTime(2036, 1, 1, 00, 00),
        theme: DatePickerTheme(
          doneStyle: TextStyles.primaryColor28,
          cancelStyle: TextStyles.textNormal28,
          itemStyle: TextStyles.primaryColor36,
        ),
        currentTime: currentTime ?? DateTime.now(),
        onChanged: (date) {}, onConfirm: (date) {
      currentTime = date;
      loadingTime = DateUtil.formatDate(currentTime, format: DataFormats.y_mo_d_h_m);
      loginEnabled.value = isCanSubmit();
      baseState!.setSafeState();
    }, locale: LocaleType.zh);
  }

  chooseWarehouse() {
    requestUniversal<WarehouseEntity>(Apis.WAREHOUSE, method: FBResultFul.GET,
        resultSuccessListCall: (list) async {
      var callbackSuppliersEntity = await Get.toNamed(Routers.chooseWarehousePage,
          arguments: {'Warehouse': list, 'SelectedWarehouse': warehouse.value});
      if (callbackSuppliersEntity != null && warehouse.value != callbackSuppliersEntity) {
        warehouse.value = callbackSuppliersEntity;
        loginEnabled.value = isCanSubmit();
        baseState!.setSafeState();
      }
    });
  }

  chooseSupplier() {
    requestUniversal<SuppliersEntity>(Apis.SUPPLIERS,
        method: FBResultFul.GET,
        queryParameters: {"supplierType": 'LOGISTICS'}, resultSuccessListCall: (list) async {
      var callbackSuppliersEntity = await Get.toNamed(Routers.chooseSupplierPage, arguments: {
        'Supplier': list,
        'SelectedSupplier': supplier.value,
        'title': MultiLanguage.carrier.tr,
      });
      if (callbackSuppliersEntity != null && supplier.value != callbackSuppliersEntity) {
        supplier.value = callbackSuppliersEntity;
        car.value = null;
        driver.value = null;
        loginEnabled.value = isCanSubmit();
        baseState!.setSafeState();
      }
    });
  }

  chooseAccountRule() {
    requestUniversal<AccountRuleEntity>(Apis.ACCOUNT_RULE, method: FBResultFul.GET,
        resultSuccessListCall: (list) async {
      singlePicker(context!, selectData: accountRuleEntity.value ?? list[0], data: list,
          onConfirm: (var data, int position) {
        accountRuleEntity.value = data as AccountRuleEntity;
        freight.value = accountRuleEntity.value!.unitPrice * commodityQuantity.value;
        loginEnabled.value = isCanSubmit();
        baseState!.setSafeState();
      });
    });
  }

  chooseCar() {
    if (supplier.value == null) {
      ToastUtil.waring(MultiLanguage.pleaseSelectACarrierFirst.tr);
      return;
    }
    requestUniversal<CarEntity>(Apis.CARS,
        method: FBResultFul.GET,
        queryParameters: {'supplierId': supplier.value!.id}, resultSuccessListCall: (list) async {
      var callbackSuppliersEntity = await Get.toNamed(Routers.carListPage,
          arguments: {'Supplier': list, 'SelectedSupplier': car.value});
      if (callbackSuppliersEntity != null && car.value != callbackSuppliersEntity) {
        car.value = callbackSuppliersEntity;
        loginEnabled.value = isCanSubmit();
        baseState!.setSafeState();
      }
    });
  }

  chooseDriver() {
    if (supplier.value == null) {
      ToastUtil.waring(MultiLanguage.pleaseSelectACarrierFirst.tr);
      return;
    }
    requestUniversal<DriverEntity>(Apis.DRIVERS,
        method: FBResultFul.GET,
        queryParameters: {'supplierId': supplier.value!.id}, resultSuccessListCall: (list) async {
      var callbackSuppliersEntity = await Get.toNamed(Routers.driverListPage,
          arguments: {'Supplier': list, 'SelectedSupplier': driver.value});
      if (callbackSuppliersEntity != null && driver.value != callbackSuppliersEntity) {
        driver.value = callbackSuppliersEntity;
        loginEnabled.value = isCanSubmit();
        baseState!.setSafeState();
      }
    });
  }

  platoon() {
    requestUniversal<Object>(Apis.DISTRIBUTION,
        tipSuccess: MultiLanguage.platoonSuccess.tr,
        method: FBResultFul.POST,
        params: {
          'carrierId': supplier.value!.id,
          'carId': car.value!.id,
          'driverId': driver.value!.id,
          'accountRuleId': accountRuleEntity.value!.id,
          'freightAmt': freight.value,
          'distributionDetailReqList': distributionDetailReqList,
          'goodsNumber': commodityQuantity.value,
          'loadingWarehouseId': warehouse.value!.id,
          'loadingTime': loadingTime,
        }, resultSuccessCallNoting: () async {
      callback.call();
      GetHelper.back();
    });
  }

  bool isCanSubmit() {
    if (supplier.value == null ||
        car.value == null ||
        driver.value == null ||
        driver.value == null ||
        warehouse.value == null ||
        loadingTime.isEmpty) {
      return false;
    } else {
      return true;
    }
  }

  @override
  void onClose() {
    super.onClose();
    supplier.close();
  }
}
